<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2019-2-12
 */

namespace app\admin\controller;

use think\Page;
use think\Db;
use think\Config;
use app\admin\logic\MemberLogic;

class Member extends Base {

    public $userConfig = [];

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
        /*会员中心数据表*/
        $this->users_db        = Db::name('users');         // 会员信息表
        $this->users_list_db   = Db::name('users_list');    // 会员资料表
        $this->users_level_db  = Db::name('users_level');   // 会员等级表
        $this->users_config_db = Db::name('users_config');  // 会员配置表
        $this->users_money_db  = Db::name('users_money');   // 会员充值表
        $this->field_type_db   = Db::name('field_type');    // 字段属性表
        $this->users_parameter_db = Db::name('users_parameter'); // 会员属性表
        $this->users_type_manage_db = Db::name('users_type_manage'); // 会员属性表
        /*结束*/

        /*订单中心数据表*/
        $this->shop_address_db   = Db::name('shop_address');    // 会员地址表
        $this->shop_cart_db      = Db::name('shop_cart');       // 会员购物车表
        $this->shop_order_db     = Db::name('shop_order');      // 会员订单主表
        $this->shop_order_log_db = Db::name('shop_order_log');  // 会员订单操作记录表
        $this->shop_order_details_db = Db::name('shop_order_details');  // 会员订单副表
        /*结束*/

        // 是否开启支付功能设置
        $this->userConfig = getUsersConfigData('all');
        $this->assign('userConfig', $this->userConfig);

        // 模型是否开启
        $channeltype_row = \think\Cache::get('extra_global_channeltype');
        $this->assign('channeltype_row', $channeltype_row);
    }

    // 会员列表
    public function users_index()
    {
        $list = array();

        $param = input('param.');
        $condition = array();
        // 应用搜索条件
        foreach (['keyword','origin_type','level','is_lock'] as $key) {
            if (isset($param[$key]) && $param[$key] !== '') {
                if ($key == 'keyword') {
                    $condition['a.username|a.nickname|a.mobile'] = array('LIKE', "%{$param[$key]}%");
                } else {
                    $condition['a.'.$key] = array('eq', $param[$key]);
                }
            }
        }
        if ($param['is_lock'] === 1 || $param['is_lock'] === 0){
            $condition['a.is_lock'] = $param['is_lock'];
        }

        // 注册时间查询
        if (!empty($param['add_time'])) {
            $add_time = explode('~', $param['add_time']);
            $start = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]).' 23:59:59');
            $condition['a.reg_time'] = ['between', "$start, $finish"];
        }

        // if (!empty($param['time_begin']) && !empty($param['time_end'])){
        //     $param['time_begin'] = strtotime($param['time_begin']);
        //     $param['time_end'] = strtotime($param['time_end'])+86400;
        //     $condition['a.reg_time'] = ['between',[$param['time_begin'],$param['time_end']]];
        // }else if (!empty($param['time_begin']) && empty($param['time_end'])){
        //     $param['time_begin'] = strtotime($param['time_begin']);
        //     $condition['a.reg_time'] = ['>',$param['time_begin']];
        // }else if (empty($param['time_begin']) && !empty($param['time_end'])){
        //     $param['time_end'] = strtotime($param['time_end']);
        //     $condition['a.reg_time'] = ['<',$param['time_end']];
        // }

        $condition['a.is_del'] = 0;
        $condition['a.is_real'] = 1;

        // 自定义排序
        $orderby = input('param.orderby/s');
        $orderway = input('param.orderway/s');
        if (!empty($orderby) && !empty($orderway)) {
            $orderby = "a.{$orderby} {$orderway}, a.users_id desc";
        } else {
            $orderby = "a.users_id desc";
        }

        $count = $this->users_db->alias('a')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));
        $list = $this->users_db->field('a.*,b.level_name')
            ->alias('a')
            ->join('__USERS_LEVEL__ b', 'a.level = b.level_id', 'LEFT')
            ->where($condition)
            ->order($orderby)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        $users_ids = get_arr_column($list,'users_id');
        //消费订单统计
        $order_count = Db::name('shop_order')->where(['users_id'=>['IN', $users_ids]])->where('order_status','in',[1,2,3])
            ->group('users_id')->field('count(order_id) as count,users_id,max(pay_time) as pay_time,sum(pay_use_cash) as total_amount')->getAllWithIndex('users_id');
        $recharge_count = Db::name('users_money')->where(['users_id'=>['IN', $users_ids]])->where('cause_type',1)->where('status','in',[2,3])
            ->group('users_id')->field('sum(money) as total_amount,users_id')->getAllWithIndex('users_id');
        foreach ($list as $key => $val) {
            $list[$key]['total_order'] = !empty($order_count[$val['users_id']]) ? $order_count[$val['users_id']]['count'] : 0;
            $order_total_amount =  !empty($order_count[$val['users_id']]) ? $order_count[$val['users_id']]['total_amount'] : 0;
            $recharge_total_amount =  !empty($recharge_count[$val['users_id']]) ? $recharge_count[$val['users_id']]['total_amount'] : 0;
            $list[$key]['total_amount'] = $order_total_amount + $recharge_total_amount;
            $list[$key]['pay_time'] = !empty($order_count[$val['users_id']]) ? $order_count[$val['users_id']]['pay_time'] : '';
        }
        /*微信登录插件*/
        $wxlogin = [];
        if (is_dir('./weapp/WxLogin/')) {
            $wxlogin = Db::name('weapp_wxlogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('wxlogin',$wxlogin);
        /*end*/

        /*QQ登录插件*/
        $qqlogin = [];
        if (is_dir('./weapp/QqLogin/')) {
            $qqlogin = Db::name('weapp_qqlogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('qqlogin',$qqlogin);
        /*end*/

        /*微博登录插件*/
        $wblogin = [];
        if (is_dir('./weapp/Wblogin/')) {
            $wblogin = Db::name('weapp_wblogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('wblogin',$wblogin);
        /*end*/

        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pager',$Page);// 赋值分页集

        $LevelData = Db::name('users_level')->field('level_id, level_name')->cache(true, EYOUCMS_CACHE_TIME, "users_level")->getAllWithIndex('level_id');
        $this->assign('level', $LevelData);

        //今日新增会员
        $countArr['t_users'] = Db::name('users')->whereTime('reg_time','today')->count('users_id');
        //昨日新增会员
        $countArr['y_users'] = Db::name('users')->whereTime('reg_time','yesterday')->count('users_id');
        //今日下单会员
        $countArr['t_buy'] = Db::name('shop_order')->whereTime('pay_time','today')->where('order_status','in',[1,2,3])->group('users_id')->count('users_id');
        //昨日下单会员
        $countArr['y_buy'] = Db::name('shop_order')->whereTime('pay_time','yesterday')->where('order_status','in',[1,2,3])->group('users_id')->count('users_id');
        //今日充值会员
        $countArr['t_recharge'] = Db::name('users_money')->whereTime('add_time','today')->where('cause_type',1)->where('status','in',[1,2,3])->group('users_id')->count('users_id');
        //昨日充值会员
        $countArr['y_recharge'] = Db::name('users_money')->whereTime('add_time','yesterday')->where('cause_type',1)->where('status','in',[1,2,3])->group('users_id')->count('users_id');
        //今日领券会员
        $countArr['t_coupon'] = Db::name('shop_coupon_use')->whereTime('get_time','today')->count('users_id');
        //昨日领券会员
        $countArr['y_coupon'] = Db::name('shop_coupon_use')->whereTime('get_time','yesterday')->count('users_id');
        //下单会员数
        $countArr['buy'] = Db::name('shop_order')->where('order_status','in',[1,2,3])->group('users_id')->count('users_id');
        $total_users = Db::name('users')->where('is_del',0)->count('users_id');
        $countArr['nobuy'] = $total_users - $countArr['buy'];
        $this->assign('statistics', $countArr);

        return $this->fetch();
    }

    // 会员批量新增
    public function users_batch_add()
    {
        if (IS_POST) {
            $post = input('post.');

            $username = $post['username'];
            if (empty($username)) {
                $this->error('用户名不能为空！');
            }

            if (empty($post['password'])) {
                $this->error('登录密码不能为空！');
            }

            if (!empty($this->userConfig['level_member_upgrade']) && 1 == $this->userConfig['level_member_upgrade']) {
                if (1 != $post['level'] && !preg_match("/^([0-9]+)$/i", $post['level_maturity_days'])) {
                    $this->error('请填写会员有效期天数！');
                }
            }
            $post['level_maturity_days'] = intval($post['level_maturity_days']);

            $password = func_encrypt($post['password'], false, pwd_encry_type('bcrypt'));

            $usernameArr = explode("\r\n", $username);
            $usernameArr = array_filter($usernameArr);//去除数组空值
            $usernameArr = array_unique($usernameArr); //去重

            $addData = [];
            $usernameList = $this->users_db->where([
                    'username'  => ['IN', $usernameArr],
                ])->column('username');
            foreach ($usernameArr as $key => $val) {
                if(trim($val) == '' || empty($val) || in_array($val, $usernameList) || !preg_match("/^[\x{4e00}-\x{9fa5}\w\-\_\@\#]{2,30}$/u", $val))
                {
                    continue;
                }

                $addData[] = [
                    'username'       => $val,
                    'nickname'       => $val,
                    'password'       => $password,
                    'level'          => $post['level'],
                    'register_place' => 1,
                    'level_maturity_days'   => $post['level_maturity_days'],
                    'open_level_time'   => getTime(),
                    'reg_time'       => getTime(),
                    'reg_ip' => clientIP(),
                    'head_pic'       => ROOT_DIR . '/'.$this->public_path.'static/common/images/dfboy.png',
                ];
            }
            if (!empty($addData)) {
                $rdata = model('Member')->saveAll($addData);
                if (!empty($rdata)) {
                    adminLog('批量新增会员：'.implode(',', get_arr_column($addData, 'username')));
                    // 更新username
                    foreach ($rdata as $k1 => $v1) {
                        $users_id_new = $v1->getData('users_id');
                        update_username($users_id_new);
                    }
                    $this->success('操作成功！', url('Member/users_index'));
                } else {
                    $this->error('操作失败');
                }
            } else {
                $this->success('操作成功！', url('Member/users_index'));
            }
        }

        $user_level = $this->users_level_db->field('level_id,level_name')
            ->order('level_value asc')
            ->select();
        $this->assign('user_level',$user_level);

        return $this->fetch();
    }

    // 会员编辑
    public function users_edit()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['users_id'] = intval($post['users_id']);
            $users_id = $post['users_id'];

            $post['head_pic'] = htmlspecialchars_decode($post['head_pic']);

            if (isset($post['users_money'])) {
                $users_money = input('post.users_money/f');
                $post['users_money'] = (99999999 < $users_money) ? 99999999 : $users_money;
            }

            if (!empty($post['password'])) {
                $post['password'] = func_encrypt($post['password'], false, pwd_encry_type('bcrypt'));
            } else {
                unset($post['password']);
            }

            $ParaData = [];
            if (is_array($post['users_'])) {
                $ParaData = $post['users_'];
            }
            unset($post['users_']);

            // 处理提交的会员属性中邮箱和手机是否已存在
            // isRequired方法传入的参数有2个
            // 第一个必须传入提交的会员属性数组
            // 第二个users_id，注册时不需要传入，修改时需要传入。
            $RequiredData = model('Member')->isRequired($ParaData,$users_id);
            if ($RequiredData) {
                $this->error($RequiredData);
            }

            $users_where = [
                'users_id' => $users_id,
            ];
            $userinfo = $this->users_db->where($users_where)->find();

            $post['update_time'] = getTime();
            if ($post['level'] != $userinfo['level']){
                $post['open_level_time'] = getTime();
            }

            unset($post['username']);
            $r = $this->users_db->where($users_where)->update($post);
            if ($r) {
                $row2 = $this->users_parameter_db->field('para_id,name,dtype')->getAllWithIndex('name');
                foreach ($ParaData as $key => $value) {
                    $data    = [];
                    $para_id = intval($row2[$key]['para_id']);
                    $where   = [
                        'users_id' => $post['users_id'],
                        'para_id'  => $para_id,
                    ];
                    if ('checkbox' == $row2[$key]['dtype']){
                        $data['info']        = implode(",",$value);
                    }else{
                        $data['info']        = $value;
                    }
                    $data['update_time'] = getTime();

                    // 若信息表中无数据则添加
                    $row = $this->users_list_db->where($where)->count();
                    if (empty($row)) {
                        $data['users_id'] = $post['users_id'];
                        $data['para_id']  = $para_id;
                        $data['add_time'] = getTime();
                        $this->users_list_db->add($data);
                    } else {
                        $this->users_list_db->where($where)->update($data);
                    }
                }

                // 查询属性表的手机号码和邮箱地址，同步修改会员信息。
                $UsersListData = model('Member')->getUsersListData('*',$users_id);
                $UsersListData['update_time'] = getTime();
                $this->users_db->where($users_where)->update($UsersListData);

                /*同步头像到管理员表对应的管理员*/
                $syn_admin_id = $this->users_db->where(['users_id'=>$post['users_id']])->getField('admin_id');
                if (!empty($syn_admin_id)) {
                    Db::name('admin')->where(['admin_id'=>$syn_admin_id])->update([
                        'head_pic'  => $post['head_pic'],
                        'update_time'   => getTime(),
                    ]);
                }
                /*end*/

                \think\Cache::clear('users_list');

                adminLog('编辑会员'.$users_id.'：'.$userinfo['username']);
                $this->success('操作成功', url('Member/users_index'));
            }else{
                $this->error('操作失败');
            }
        }

        $assign_data = [];
        $users_id = input('param.id/d');

        // 会员信息
        $info = $this->users_db->where([
                'users_id'  => $users_id,
            ])->find();

        $assign_data['info'] = $info;

        /*微信登录插件*/
        if (is_dir('./weapp/WxLogin/')) {
            $assign_data['info']['wxlogin'] = Db::name('weapp_wxlogin')->where(['users_id'=>$users_id])->find();
        }
        /*end*/

        /*QQ登录插件*/
        if (is_dir('./weapp/QqLogin/')) {
            $assign_data['info']['qqlogin'] = Db::name('weapp_qqlogin')->where(['users_id'=>$users_id])->find();
        }
        /*end*/

        // 等级信息
        $assign_data['level'] = $this->users_level_db->field('level_id,level_name')
            ->order('level_value asc')
            ->select();

        // 属性信息
        $assign_data['users_para'] = model('Member')->getDataParaList($users_id);
        // 积分
        $assign_data['scoreCofing'] = getUsersConfigData('score');

        // 上一个页面来源
        $from = input('param.from/s');
        if ('money_index' == $from) {
            $backurl = url('Member/money_index');
        } else {
            $backurl = url('Member/users_index');
        }
        $assign_data['backurl'] = $backurl;

        // 是否弹窗打开
        $iframe = input('param.iframe/d',0);
        $assign_data['iframe'] = $iframe;

        $assign_data['users_lock_model'] = config('global.users_lock_model');

        //订单信息
        $assign_data['order_count'] = Db::name('shop_order')->where('order_status',3)->where('users_id',$users_id)->field('count(*) as count,sum(order_amount) as sum')->select();
        $assign_data['refund_count'] = Db::name('shop_order_service')
            ->where('users_id',$users_id)
            ->where('service_type','in',[2,3])
            ->where('status','not in',[3,8,9])
            ->field('count(*) as count,sum(refund_price) as sum')->select();

        //收藏夹
        $assign_data['collect_count'] = Db::name('users_collection')->where('users_id',$users_id)->count('id');
        //浏览记录
        $assign_data['footprint_count'] = Db::name('users_footprint')->where('users_id',$users_id)->count('id');
        //判断是否有过期优惠券
        Db::name('shop_coupon_use')->where(['users_id' => $users_id, 'use_status' => 0])->where('end_time', '<', getTime())->update(['use_status' => 2, 'update_time' => getTime()]);
        $assign_data['coupon_count'] = Db::name('shop_coupon_use')->where(['users_id' => $users_id, 'use_status' => 0])->count();

        $this->assign($assign_data);

        return $this->fetch();
    }

    // 会员删除
    public function users_del()
    {
        $users_id = input('del_id/a');
        $users_id = eyIntval($users_id);
        if (IS_AJAX_POST && !empty($users_id)) {
            // 删除统一条件
            $Where = [
                'users_id'  => ['IN', $users_id],
            ];

            $result = $this->users_db->field('username')->where($Where)->select();
            $username_list = get_arr_column($result, 'username');

            $return = $this->users_db->where($Where)->delete();
            if (false !== $return) {
                // // 删除会员下的属性
                $this->users_list_db->where($Where)->delete();
                //删除微信用户表
                Db::name('wx_users')->where($Where)->delete();
                \think\Cache::clear('users_list');
                adminLog('删除会员：'.implode(',', $username_list));
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    public function users_handdle()
    {
        $users_id = input('del_id/a');
        $users_id = eyIntval($users_id);
        $action = input('action/s');
        if (IS_AJAX_POST && !empty($users_id) && !empty($action)) {
            $where = [
                'users_id'  => ['IN', $users_id],
            ];
            if ('set_is_lock' == $action){
                $res = Db::name('users')->where($where)->update(['is_lock'=>1,'update_time'=>getTime()]);
                if (false !== $res) {
                    adminLog('设置黑名单：'.implode(',', $users_id));
                    $this->success('设置黑名单成功');
                }else{
                    $this->error('设置黑名单失败');
                }
            }else if ('cancel_is_lock' == $action){
                $res = Db::name('users')->where($where)->update(['is_lock'=>0,'update_time'=>getTime()]);
                if (false !== $res) {
                    adminLog('取消黑名单：'.implode(',', $users_id));
                    $this->success('取消黑名单成功');
                }else{
                    $this->error('取消黑名单失败');
                }
            }
        }
        $this->error('参数有误');
    }

    //会员备注
    public function edit_remark()
    {
        $users_id = input('post.users_id/d');
        $remark = input('post.remark/s');
        if (empty($users_id)) $this->error('缺少必要参数');
        $res = Db::name('users')->where('users_id',$users_id)->update(['remark'=>$remark,'update_time'=>getTime()]);
        if (false !== $res){
            adminLog("会员备注：{$remark}");
            $this->success('保存成功');
        }
        $this->error('保存失败');
    }

    // 导出会员
    public function users_excel_export()
    {
        // 设置最大内存
        ini_set("memory_limit", "-1");

        // 防止php超时
        function_exists('set_time_limit') && set_time_limit(0);

        // 执行操作
        if (IS_AJAX_POST) {
            $list = array();

            $param = input('param.');
            $condition = array();
            // 应用搜索条件
            foreach (['keyword','origin_type','level','is_lock'] as $key) {
                if (isset($param[$key]) && $param[$key] !== '') {
                    if ($key == 'keyword') {
                        $condition['a.username|a.nickname|a.mobile'] = array('LIKE', "%{$param[$key]}%");
                    } else {
                        $condition['a.'.$key] = array('eq', $param[$key]);
                    }
                }
            }
            if ($param['is_lock'] === 1 || $param['is_lock'] === 0){
                $condition['a.is_lock'] = $param['is_lock'];
            }
            if (!empty($param['time_begin']) && !empty($param['time_end'])){
                $param['time_begin'] = strtotime($param['time_begin']);
                $param['time_end'] = strtotime($param['time_end'])+86400;
                $condition['a.reg_time'] = ['between',[$param['time_begin'],$param['time_end']]];
            }else if (!empty($param['time_begin']) && empty($param['time_end'])){
                $param['time_begin'] = strtotime($param['time_begin']);
                $condition['a.reg_time'] = ['between',[$param['time_begin'],getTime()]];
            }else if (empty($param['time_begin']) && !empty($param['time_end'])){
                $param['time_end'] = strtotime($param['time_end']);
                $condition['a.reg_time'] = ['<',$param['time_end']];
            }

            $condition['a.is_del'] = 0;

            // 自定义排序
            $orderby = input('param.orderby/s');
            $orderway = input('param.orderway/s');
            if (!empty($orderby) && !empty($orderway)) {
                $orderby = "a.{$orderby} {$orderway}, a.users_id desc";
            } else {
                $orderby = "a.users_id desc";
            }

            $list = $this->users_db
                ->field('a.username,a.nickname,a.mobile,a.sex,a.users_money,a.scores,a.total_amount,a.last_login,a.reg_time,b.level_name')
                ->alias('a')
                ->join('__USERS_LEVEL__ b', 'a.level = b.level_id', 'LEFT')
                ->where($condition)
                ->order($orderby)
                ->select();
            if (empty($list)) $this->error('当前没有可导出数据');

            $users_ids = get_arr_column($list,'users_id');
            $order_count = Db::name('shop_order')->where(['users_id'=>['IN', $users_ids]])->where('order_status','in',[1,2,3])
                ->group('users_id')->field('count(order_id) as count,users_id')->getAllWithIndex('users_id');
            foreach ($list as $key => $val) {
                $list[$key]['total_order'] = !empty($order_count[$val['users_id']]) ? $order_count[$val['users_id']]['count'] : 0;
            }
            $data[] = ['username'=>'会员账号','nickname'=>'会员昵称','mobile'=>'手机号码','sex'=>'性别','level_name'=>'会员等级','users_money'=>'余额',
                'scores'=>'积分','total_order'=>'累计成交订单','total_amount'=>'累计成交金额','last_login'=>'上次登录时间','reg_time'=>'注册时间'];
            $data = array_merge($data,$list);

            vendor('PHPExcel.Classes.PHPExcel');
            $objPHPExcel = new \PHPExcel();      //实例化Excel类
            $objPHPExcel->getDefaultStyle()->getFont()->setName("宋体");//设置字体
            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->setTitle('会员信息');//设置Sheet表名称


            $columnWidth = [
                ['col'=>'A','width'=>'20'],
                ['col'=>'B','width'=>'20'],
                ['col'=>'C','width'=>'15'],
                ['col'=>'D','width'=>'10'],
                ['col'=>'E','width'=>'15'],
                ['col'=>'F','width'=>'15'],
                ['col'=>'G','width'=>'15'],
                ['col'=>'H','width'=>'15'],
                ['col'=>'I','width'=>'15'],
                ['col'=>'J','width'=>'23'],
                ['col'=>'K','width'=>'23'],
            ];
            foreach ($columnWidth as $k => $v){
                //设置单元格宽
                $objPHPExcel->getActiveSheet()->getColumnDimension($v['col'])->setWidth($v['width']);
            }

            //写入到第一个sheet
            $col = 0;
            if (!empty($data)){
                foreach ($data as $k => $v) {
                    $col = $col + 1;
                    if ($col > 1){
                        $v['last_login'] = date('Y-m-d H:i:s',$v['last_login']);
                        $v['reg_time'] = date('Y-m-d H:i:s',$v['reg_time']);
                    }
                    $objPHPExcel->getActiveSheet()->getStyle('A' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('B' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('C' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('D' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('E' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('F' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('G' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('H' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('I' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('J' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
                    $objPHPExcel->getActiveSheet()->getStyle('K' . $col)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中

                    $objPHPExcel->getActiveSheet()->setcellvalue('A' . $col, $v['username']);//第A列 第$k行
                    $objPHPExcel->getActiveSheet()->setcellvalue('B' . $col, $v['nickname']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('C' . $col, $v['mobile']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('D' . $col, $v['sex']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('E' . $col, $v['level_name']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('F' . $col, $v['users_money']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('G' . $col, $v['scores']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('H' . $col, $v['total_order']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('I' . $col, $v['total_amount']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('J' . $col, $v['last_login']);
                    $objPHPExcel->getActiveSheet()->setcellvalue('K' . $col, $v['reg_time']);
                }
            }

            $FileName = 'users-info';

            // 文件目录
            $ExcelPath = UPLOAD_PATH . 'excel/';
            // 保存前清空删除原先的excel
            delFile(UPLOAD_PATH . 'excel/', true);
            // 创建文件夹
            @mkdir($ExcelPath, 0777, true);
            // excel文件路径
            $filePath = $ExcelPath . $FileName .'-'.getTime(). '.xlsx';

            vendor('PHPExcel.Classes.PHPExcel.IOFactory');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save($filePath);// 保存excel文件
            // 返回excel文件路径到AJAX下载
            $path = request()->domain() . ROOT_DIR . '/' . $filePath;
        }

        if (!empty($path)) {
            $this->success('正在下载', $path);
        } else {
            $this->error('导出失败');
        }
    }

    // 属性列表
    public function attr_index()
    {
        //属性数据
        $info = $this->users_parameter_db->field('a.*,a.title,b.title as dtypetitle')
            ->alias('a')
            ->join('__FIELD_TYPE__ b', 'a.dtype = b.name', 'LEFT')
            ->order('a.is_system desc,a.sort_order asc,a.para_id desc')
            ->select();
        foreach ($info as $key => $value) {
            if ('email' == $value['dtype']) {
                $info[$key]['dtypetitle'] = '邮箱地址';
            } else if ('mobile' == $value['dtype']) {
                $info[$key]['dtypetitle'] = '手机号码';
            }else if ('datetime' == $value['dtype']) {
                $info[$key]['dtypetitle'] = '日期和时间';
            }
        }
        $this->assign('info',$info);
        return $this->fetch();
    }

    // 属性添加
    public function attr_add()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['title'] = trim($post['title']);

            if (empty($post['title'])) {
                $this->error('属性标题不能为空！');
            }
            if (empty($post['dtype'])) {
                $this->error('请选择属性类型！');
            }

            $count = $this->users_parameter_db->where([
                    'title'=>$post['title']
                ])->count();
            if (!empty($count)) {
                $this->error('属性标题已存在！');
            }

            $post['dfvalue']     = str_replace('，', ',', $post['dfvalue']);
            $post['dfvalue'] = trim($post['dfvalue'], ',');

            /*判断默认值是否含有重复值*/
            if (in_array($post['dtype'], ['radio','checkbox','select'])) {
                if (!empty($post['dfvalue'])){
                    $dfvalue_arr = [];
                    $dfvalue_arr = explode(',', $post['dfvalue']);
                    foreach ($dfvalue_arr as &$v) {
                        $v = trim($v);
                    }
                    if (count($dfvalue_arr) != count(array_unique($dfvalue_arr))) {
                        $this->error('默认值不能含有相同的值！');
                    }
                }
            }
            /*end*/

            $post['add_time'] = getTime();
            $post['sort_order'] = '100';
            $para_id = $this->users_parameter_db->insertGetId($post);
            if (!empty($para_id)) {
                $name = 'para_'.$para_id;
                $return = $this->users_parameter_db->where('para_id',$para_id)
                    ->update([
                        'name'  => $name,
                        'update_time'   => getTime(),
                    ]);
                if ($return) {
                    adminLog('新增会员属性：'.$post['title']);
                    $this->success('操作成功',url('Member/attr_index'));
                }
            }
            $this->error('操作失败');
        }

        $field = $this->field_type_db->field('name,title,ifoption')
            ->where([
                'name'  => ['IN', ['text','checkbox','multitext','radio','select','img','file','datetime']]
            ])
            ->select();
        $this->assign('field',$field);
        return $this->fetch();
    }

    // 属性修改
    public function attr_edit()
    {
        $para_id = input('param.id/d');

        if (IS_POST && !empty($para_id)) {
            $post = input('post.');
            $post['title'] = trim($post['title']);

            if (empty($post['title'])) {
                $this->error('属性标题不能为空！');
            }
            if (empty($post['dtype'])) {
                $this->error('请选择属性类型！');
            }

            $count = $this->users_parameter_db->where([
                    'title'     => $post['title'],
                    'para_id'   => ['NEQ', $para_id],
                ])->count();
            if ($count) {
                $this->error('属性标题已存在！');
            }

            $post['dfvalue'] = str_replace('，', ',', $post['dfvalue']);
            $post['dfvalue'] = trim($post['dfvalue'], ',');

            /*判断默认值是否含有重复值*/
            if (in_array($post['dtype'], ['radio','checkbox','select'])) {
                if (!empty($post['dfvalue'])){
                    $dfvalue_arr = [];
                    $dfvalue_arr = explode(',', $post['dfvalue']);
                    foreach ($dfvalue_arr as &$v) {
                        $v = trim($v);
                    }
                    if (count($dfvalue_arr) != count(array_unique($dfvalue_arr))) {
                        $this->error('默认值不能含有相同的值！');
                    }
                }
            }
            /*end*/

            $post['update_time'] = getTime();
            $return = $this->users_parameter_db->where([
                    'para_id'   => $para_id,
                ])->update($post);
            if ($return) {
                adminLog('编辑会员属性：'.$post['title']);
                $this->success('操作成功',url('Member/attr_index'));
            }else{
                $this->error('操作失败');
            }
        }

        $info = $this->users_parameter_db->where([
                'para_id'   => $para_id,
            ])->find();
        $this->assign('info',$info);

        $field = $this->field_type_db->field('name,title,ifoption')
            ->where([
                'name'  => ['IN', ['text','checkbox','multitext','radio','select','img','file','datetime']]
            ])
            ->select();
        $this->assign('field',$field);

        return $this->fetch();
    }

    // 属性删除
    public function attr_del()
    {
        $para_id = input('del_id/a');
        $para_id = eyIntval($para_id);

        if (IS_AJAX_POST && !empty($para_id)) {
            $result = $this->users_parameter_db->field('title')
                ->where([
                    'para_id'  => ['IN', $para_id],
                ])
                ->select();
            $title_list = get_arr_column($result, 'title');

            // 删除会员属性表数据
            $return = $this->users_parameter_db->where([
                    'para_id'  => ['IN', $para_id],
                ])->delete();

            if ($return) {
                // 删除会员属性信息表数据
                $this->users_list_db->where([
                        'para_id'  => ['IN', $para_id],
                    ])->delete();
                \think\Cache::clear('users_list');
                adminLog('删除会员属性：'.implode(',', $title_list));
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // 功能设置
    public function users_config()
    {
        if (IS_POST) {
            $post = input('post.');

            // 邮件验证的检测
            if (2 == $post['users']['users_verification']) {
                $users_config_email = $this->users_config_email();
                if (!empty($users_config_email)) {
                   $this->error($users_config_email);
                }
            }
            // 第三方登录
            if (!empty($post['oauth']['oauth_open']) && 1 == $post['oauth']['oauth_open']) {
                empty($post['oauth']['oauth_qq']) && $post['oauth']['oauth_qq'] = 0;
                empty($post['oauth']['oauth_weixin']) && $post['oauth']['oauth_weixin'] = 0;
                empty($post['oauth']['oauth_weibo']) && $post['oauth']['oauth_weibo'] = 0;
            }

            /*前台登录超时*/
            $users_login_expiretime = $post['users']['users_login_expiretime'];
            $login_expiretime_old = $post['users']['login_expiretime_old'];
            unset($post['users']['login_expiretime_old']);
            if ($login_expiretime_old != $users_login_expiretime) {
                $users_login_expiretime = preg_replace('/^(\d{0,})(.*)$/i', '${1}', $users_login_expiretime);
                empty($users_login_expiretime) && $users_login_expiretime = config('login_expire');
                if ($users_login_expiretime > 2592000) {
                    $users_login_expiretime = 2592000; // 最多一个月
                }
                $post['users']['users_login_expiretime'] = $users_login_expiretime;
                //后台登录超时时间
                $web_login_expiretime = tpCache('global.web_login_expiretime');
                //前台和后台谁设置的时间大就用谁的做session过期时间
                $max_login_expiretime = $web_login_expiretime;
                if ($web_login_expiretime < $users_login_expiretime){
                    $max_login_expiretime = $users_login_expiretime;
                }
            }
            /*--end*/

            // 会员投稿设置
            if (!empty($this->userConfig['users_open_release'])) {
                unset($post['release_typeids']);
                unset($post['users']['is_automatic_review']);
                unset($post['users']['is_open_posts_count']);
            }

            // 会员模板切换/前台会员登录过期时间
            tpCache('web', $post['web']);

            foreach ($post as $key => $val) {
                if ('web' == $key) {
                    continue;
                }
                getUsersConfigData($key, $val);
            }

            /*更改session会员设置 - session有效期（前台登录超时）*/
            if ($login_expiretime_old != $users_login_expiretime) {
                $session_conf = [];
                $session_file = APP_PATH.'admin/conf/session_conf.php';
                if (file_exists($session_file)) {
                    require_once($session_file);
                    $session_conf_tmp = EY_SESSION_CONF;
                    if (!empty($session_conf_tmp)) {
                        $session_conf_tmp = json_decode($session_conf_tmp, true);
                        if (!empty($session_conf_tmp) && is_array($session_conf_tmp)) {
                            $session_conf = $session_conf_tmp;
                        }
                    }
                }
                $session_conf['expire'] = $max_login_expiretime;
                $str_session_conf = '<?php'.PHP_EOL.'$session_1600593464 = json_encode('.var_export($session_conf,true).');'.PHP_EOL.'define(\'EY_SESSION_CONF\', $session_1600593464);';
                @file_put_contents(APP_PATH . 'admin/conf/session_conf.php', $str_session_conf);
            }
            /*--end*/

            $this->success('操作成功');
        }

        // 获取会员配置信息
        $this->assign('info',$this->userConfig);

        // 获取会员配置信息
        $this->assign('web_users_tpl_theme', tpCache('global.web_users_tpl_theme'));

        // 左侧菜单
        $usersTplVersion = getUsersTplVersion();
        $this->assign('usersTplVersion', $usersTplVersion);

        /*允许发布文档列表的栏目*/
        $current_channel = [1,3,4,5]; // 允许投稿的模型
        $arctype = Db::name('arctype')->where([
            'current_channel' => ['in',$current_channel],
            'is_release' => 1,
        ])->field('id')->select();
        $arctype = get_arr_column($arctype,'id');
        $release_select_html = allow_release_arctype($arctype, $current_channel);
        if (empty($current_channel)){
            $release_select_html = [];
        }
        $this->assign('release_select_html',$release_select_html);
        /*--end*/

        /*模板风格列表*/
        $web_tpl_theme = config('ey_config.web_tpl_theme');
        !empty($web_tpl_theme) && $web_tpl_theme .= '/';
        $tpl_theme_list = glob('./template/'.$web_tpl_theme.'pc/users*', GLOB_ONLYDIR);
        foreach ($tpl_theme_list as $key => &$val) {
            $val = str_replace('\\', '/', $val);
            $val = preg_replace('/^(.*)\/([^\/]*)$/i', '${2}', $val);
        }
        $this->assign('tpl_theme_list', $tpl_theme_list);
        /*end*/

        return $this->fetch();
    }

    // 邮件验证的检测
    public function ajax_users_config_email()
    {
        if (IS_AJAX) {
            // 邮件验证的检测
            $users_config_email = $this->users_config_email();
            if (!empty($users_config_email)) $this->error($users_config_email);
            $this->success('检验通过');
        }
        $this->error('参数有误');
    }

    private function users_config_email(){
        // 会员属性信息
        $where = array(
            'name'      => ['LIKE', "email_%"],
            'is_system' => 1,
        );
        // 是否要为必填项
        $param = $this->users_parameter_db->where($where)->field('title,is_hidden')->find();
        if (empty($param) || 1 == $param['is_hidden']) {
            return "请先把会员属性的<font color='red'>{$param['title']}</font>设置为显示，且为必填项！";
        }

        $param = $this->users_parameter_db->where($where)->field('title,is_required')->find();
        if (empty($param) || 0 == $param['is_required']) {
            return "请先把会员属性的<font color='red'>{$param['title']}</font>设置为必填项！";
        }

        // 是否开启邮箱发送扩展
        $openssl_funcs = get_extension_funcs('openssl');
        if (!$openssl_funcs) {
            return "请联系空间商，开启php的 <font color='red'>openssl</font> 扩展！";
        }

        $send_email_scene = config('send_email_scene');
        $scene = $send_email_scene[2]['scene'];

        // 自动启用注册邮件模板
        Db::name('smtp_tpl')->where([
                'send_scene'    => $scene,
            ])->update([
                'is_open'       => 1,
                'update_time'   => getTime(),
            ]);

        // 是否填写邮件配置
        $globalConfig = tpCache('global');
        if (empty($globalConfig['smtp_user']) || empty($globalConfig['smtp_pwd'])) {
            return "请先完善<font color='red'>(邮件配置)</font>，具体步骤【基本信息】->【接口配置】->【邮件配置】";
        }

        return false;
    }

    // 手机验证的检测
    public function ajax_users_config_mobile()
    {
        if (IS_AJAX) {
            // 邮件验证的检测
            $users_config_mobile = $this->users_config_mobile();
            if (!empty($users_config_mobile)) $this->error($users_config_mobile);
            $this->success('检验通过');
        }
        $this->error('参数有误');
    }

    private function users_config_mobile(){
        // 会员属性信息
        $where = array(
            'name'      => ['LIKE', "mobile_%"],
            'is_system' => 1
        );

        // 是否要为必填项
        $param = $this->users_parameter_db->where($where)->field('title, is_hidden')->find();
        if (empty($param) || 1 == $param['is_hidden']) {
            return "请先把会员属性的<font color='red'>{$param['title']}</font>设置为显示，且为必填项！";
        }

        $param = $this->users_parameter_db->where($where)->field('title, is_required')->find();
        if (empty($param) || 0 == $param['is_required']) {
            return "请先把会员属性的<font color='red'>{$param['title']}</font>设置为必填项！";
        }

        // 自动启用注册手机模板
        Db::name('sms_template')->where([
                'send_scene'  => 0,
            ])->update([
                'is_open'     => 1,
                'update_time' => getTime()
            ]);

        // 是否填写手机短信配置
        $globalConfig = tpCache('global');
        if ( (1 == $globalConfig['sms_type'] && (empty($globalConfig['sms_appkey']) || empty($globalConfig['sms_secretkey'])))
            || (2 == $globalConfig['sms_type'] && (empty($globalConfig['sms_appid_tx']) || empty($globalConfig['sms_appkey_tx'])))
        ) {
            return "请先完善<font color='red'>(短信配置)</font>，具体步骤【基本信息】->【接口配置】->【短信配置】";
        }

        return false;
    }


    // 查询订单付款状态(微信)
    private function check_wechat_order($order_number)
    {
        if (!empty($order_number)) {
            // 引入文件
            vendor('wechatpay.lib.WxPayApi');
            vendor('wechatpay.lib.WxPayConfig');
            // 实例化加载订单号
            $input  = new \WxPayOrderQuery;
            $input->SetOut_trade_no($order_number);

            // 处理微信配置数据
            $pay_wechat_config = !empty($this->userConfig['pay_wechat_config']) ? $this->userConfig['pay_wechat_config'] : '';
            $pay_wechat_config = unserialize($pay_wechat_config);
            $config_data['app_id'] = $pay_wechat_config['appid'];
            $config_data['mch_id'] = $pay_wechat_config['mchid'];
            $config_data['key']    = $pay_wechat_config['key'];

            // 实例化微信配置
            $config = new \WxPayConfig($config_data);
            $wxpayapi = new \WxPayApi;

            // 返回结果
            $result = $wxpayapi->orderQuery($config, $input);

            // 判断结果
            if ('ORDERNOTEXIST' == $result['err_code'] && 'FAIL' == $result['result_code']) {
                return '订单在微信中不存在！';
            }else if ('NOTPAY' == $result['trade_state'] && 'SUCCESS' == $result['result_code']) {
                return '订单在微信中生成，但并未支付完成！';
            }else if ('SUCCESS' == $result['trade_state'] && 'SUCCESS' == $result['result_code']) {
                return '订单已使用'.$result['attach'].'完成！';
            }
        }else{
            return false;
        }
    }

    // 查询订单付款状态(支付宝)
    private function check_alipay_order($order_number,$admin_pay='',$alipay='')
    {
        if (!empty($order_number)) {
            // 引入文件
            vendor('alipay.pagepay.service.AlipayTradeService');
            vendor('alipay.pagepay.buildermodel.AlipayTradeQueryContentBuilder');

            // 实例化加载订单号
            $RequestBuilder = new \AlipayTradeQueryContentBuilder;
            $out_trade_no   = trim($order_number);
            $RequestBuilder->setOutTradeNo($out_trade_no);

            // 处理支付宝配置数据
            if (empty($alipay)) {
                $pay_alipay_config = !empty($this->userConfig['pay_alipay_config']) ? $this->userConfig['pay_alipay_config'] : '';
                if (empty($pay_alipay_config)) {
                    return false;
                }
                $alipay = unserialize($pay_alipay_config);
            }
            $config['app_id']     = $alipay['app_id'];
            $config['merchant_private_key'] = $alipay['merchant_private_key'];
            $config['charset']    = 'UTF-8';
            $config['sign_type']  = 'RSA2';
            $config['gatewayUrl'] = 'https://openapi.alipay.com/gateway.do';
            $config['alipay_public_key'] = $alipay['alipay_public_key'];

            // 实例化支付宝配置
            $aop = new \AlipayTradeService($config);

            // 返回结果
            if (!empty($admin_pay)) {
                $result = $aop->IsQuery($RequestBuilder,$admin_pay);
            }else{
                $result = $aop->Query($RequestBuilder);
            }

            $result = json_decode(json_encode($result),true);

            // 判断结果
            if ('40004' == $result['code'] && 'Business Failed' == $result['msg']) {
                // 用于支付宝支付配置验证
                if (!empty($admin_pay)) { return 'ok'; }
                // 用于订单查询
                return '订单在支付宝中不存在！';
            }else if ('10000' == $result['code'] && 'WAIT_BUYER_PAY' == $result['trade_status']) {
                return '订单在支付宝中生成，但并未支付完成！';
            }else if ('10000' == $result['code'] && 'TRADE_SUCCESS' == $result['trade_status']) {
                return '订单已使用支付宝支付完成！';
            }

            // 用于支付宝支付配置验证
            if (!empty($admin_pay) && !empty($result)) {
                if ('40001' == $result['code'] && 'Missing Required Arguments' == $result['msg']) {
                    return '商户私钥错误！';
                }
                if (!is_array($result)) {
                    return $result;
                }
            }
        }
    }

    /**
     * 版本检测更新弹窗
     */
    public function ajax_check_upgrade_version()
    {
        $memberLogic = new MemberLogic;
        $upgradeMsg = $memberLogic->checkVersion(); // 升级包消息
        $this->success('检测成功', null, $upgradeMsg);
    }

    /**
    * 一键升级
    */
    public function OneKeyUpgrade(){
        header('Content-Type:application/json; charset=utf-8');
        function_exists('set_time_limit') && set_time_limit(0);

        /*权限控制 by 小虎哥*/
        $auth_role_info = session('admin_info.auth_role_info');
        if(0 < intval(session('admin_info.role_id')) && ! empty($auth_role_info) && intval($auth_role_info['online_update']) <= 0){
            $this->error('您没有操作权限，请联系超级管理员分配权限');
        }
        /*--end*/

        $memberLogic = new MemberLogic;
        $data = $memberLogic->OneKeyUpgrade(); //升级包消息
        if (1 <= intval($data['code'])) {
            $this->success($data['msg'], null, ['code'=>$data['code']]);
        } else {
            $msg = '模板升级异常，请排查问题！';
            if (is_array($data)) {
                $msg = $data['msg'];
            }
            $this->error($msg);
        }
    }

    /**
    * 检测目录权限
    */
    public function check_authority()
    {
        $filelist = input('param.filelist/s');
        $memberLogic = new MemberLogic;
        $data = $memberLogic->checkAuthority($filelist); //检测目录权限
        if (is_array($data)) {
            if (1 == $data['code']) {
                $this->success($data['msg']);
            } else {
                $this->error($data['msg'], null, $data['data']);
            }
        } else {
            $this->error('检测模板失败', null, ['code'=>1]);
        }
    }

    // 前台会员左侧菜单
    public function ajax_menu_index()
    {
        $list = array();
        $condition = array();

        $usersTplVersion = getUsersTplVersion();
        if ('v2' == $usersTplVersion) {
            $condition['a.version'] = array('EQ', $usersTplVersion);
        } else {
            $condition['a.version'] = array('IN', ['weapp', $usersTplVersion]);
        }

        /**
         * 数据查询
         */
        $count = Db::name('users_menu')->alias('a')->where($condition)->count();// 查询满足要求的总记录数
        $Page = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $row = Db::name('users_menu')->field('a.*')
            ->alias('a')
            ->where($condition)
            ->order('a.sort_order asc, a.id asc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        $list = [];
        foreach ($row as $key => $val) {
            $list[] = $val;
        }

        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pager',$Page);// 赋值分页集

        return $this->fetch();
    }


    // 前台会员手机端底部菜单
    public function ajax_bottom_menu_index()
    {
        $list = array();
        $condition = array();

        /**
         * 数据查询
         */
        $count = Db::name('users_bottom_menu')->alias('a')->where($condition)->count();// 查询满足要求的总记录数
        $Page = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $list = Db::name('users_bottom_menu')->field('a.*')
            ->alias('a')
            ->where($condition)
            ->order('a.sort_order asc, a.id asc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        // 手机端会员中心底部菜单配置选项
        $mobile_user_bottom_menu_config = Config::get('global.mobile_user_bottom_menu_config');

        if ($mobile_user_bottom_menu_config) {
            foreach ($mobile_user_bottom_menu_config as $key=>$v) {
                switch ($v['mca']) {
                    case 'user/Level/level_centre':
                        $is_open = getUsersConfigData('level.level_member_upgrade');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/Pay/pay_account_recharge':
                        $is_open = getUsersConfigData('level.level_member_upgrade');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/Shop/shop_centre':
                        $is_open = getUsersConfigData('shop.shop_open');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/Shop/shop_cart_list':
                        $is_open = getUsersConfigData('shop.shop_open');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/UsersRelease/article_add':
                        $is_open = getUsersConfigData('users.users_open_release');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/UsersRelease/release_centre':
                        $is_open = getUsersConfigData('users.users_open_release');
                        if (!$is_open || $is_open != 1) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                    case 'user/Download/index':
                        $is_open = Db::name("channeltype")->where(['nid'=>'download','status'=>1])->value("id");
                        if (!$is_open) unset($mobile_user_bottom_menu_config[$key]);
                        break;
                }
            }
        }

        $this->assign('mobile_user_bottom_menu_config',$mobile_user_bottom_menu_config);

        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pager',$Page);// 赋值分页集

        return $this->fetch();
    }

    /**
     * 登录会员面板
     */
    public function syn_users_login($users_id = 0, $mca = '', $vars = [])
    {
        if (!empty($users_id)) {
            $users = Db::name('users')->field('a.*,b.level_name,b.level_value,b.discount as level_discount')
                ->alias('a')
                ->join('__USERS_LEVEL__ b', 'a.level = b.level_id', 'LEFT')
                ->where([
                    'a.users_id'        => $users_id,
                    'a.is_del'  => 0,
                ])->find();
            if (!empty($users)) {
                session('users_id',$users_id);
                session('users_login_expire', getTime()); // 登录有效期
                $url = get_homeurl($mca, $vars);
                $this->redirect($url);
            } else {
                $this->error('该用户不存在！');
            }
        }
    }

    // --------------------------视频订单------------------------------ //

    // 视频订单列表页
    public function media_index()
    {
        // 定义数组
        $condition = [];

        // 订单状态搜索
        $order_status = input('param.order_status/d', 0);
        if (!empty($order_status)) $condition['a.order_status'] = intval($order_status) === 1 ? intval($order_status) : 0;

        // 订单号或用户名搜索
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $condition['a.order_code|b.username'] = ['LIKE', "%{$keywords}%"];

        // 支付方式查询
        $pay_name = input('pay_name/s', '');
        if (!empty($pay_name)) $condition['a.pay_name'] = $pay_name;

        // 时间检索条件
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $condition['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $condition['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $condition['a.add_time'] = array('elt', $end);
        }

        // 分页查询
        $count = Db::name('media_order')->alias('a')->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = Db::name('media_order')->where($condition)
            ->field('a.*, b.head_pic, b.username, b.nickname')
            ->alias('a')
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.order_id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $key => $value) {
            $value['username'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['head_pic'] = get_head_pic($value['head_pic']);
            $list[$key] = $value;
        }
        $show = $Page->show();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->assign('pager', $Page);
        // 是否开启文章付费
        $channelRow = Db::name('channeltype')->where('nid', 'in',['article','download'])->getAllWithIndex('nid');
        foreach ($channelRow as &$val){
            if (!empty($val['data'])) $val['data'] = json_decode($val['data'], true);
        }
        $this->assign('channelRow', $channelRow);

        return $this->fetch();
    }

    // 视频订单详情页
    public function media_order_details()
    {
        $order_id = input('param.order_id/d');
        if (!empty($order_id)) {
            // 查询订单信息
            $OrderData = Db::name('media_order')->field('*, product_id as aid')->find($order_id);
            // 查询会员数据
            $UsersData = $this->users_db->find($OrderData['users_id']);
            // 用于点击视频文档跳转到前台
            $array_new = get_archives_data([$OrderData], 'product_id');
            // 内页地址
            $OrderData['arcurl'] = get_arcurl($array_new[$OrderData['product_id']]);
            // 支持子目录
            $OrderData['product_litpic'] = get_default_pic($OrderData['product_litpic']);
            // 加载数据
            $this->assign('OrderData', $OrderData);
            $this->assign('UsersData', $UsersData);
            return $this->fetch();
        } else {
            $this->error('非法访问！');
        }
    }

    // 视频订单批量删除
    public function media_order_del()
    {
        $order_id = input('del_id/a');
        $order_id = eyIntval($order_id);
        if (IS_AJAX_POST && !empty($order_id)) {
            // 条件数组
            $Where = [
                'order_id'  => ['IN', $order_id],
            ];
            $result = Db::name('media_order')->field('order_code')->where($Where)->select();
            $order_code_list = get_arr_column($result, 'order_code');
            // 删除订单列表数据
            $return = Db::name('media_order')->where($Where)->delete();
            if ($return) {
                adminLog('删除订单：'.implode(',', $order_code_list));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // --------------------------视频订单------------------------------ //

    // 文章订单列表页
    public function article_index()
    {
        // 定义数组
        $condition = [];

        // 订单状态搜索
        $order_status = input('param.order_status/d', 0);
        if (!empty($order_status)) $condition['a.order_status'] = intval($order_status) === 1 ? intval($order_status) : 0;

        // 订单号或用户名搜索
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $condition['a.order_code|b.username'] = ['LIKE', "%{$keywords}%"];

        // 支付方式查询
        $pay_name = input('pay_name/s', '');
        if (!empty($pay_name)) $condition['a.pay_name'] = $pay_name;

        // 时间检索条件
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $condition['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $condition['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $condition['a.add_time'] = array('elt', $end);
        }

        // 分页查询
        $count = Db::name('article_order')->alias('a')->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = Db::name('article_order')->where($condition)
            ->field('a.*, b.head_pic, b.username, b.nickname')
            ->alias('a')
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.order_id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $key => $value) {
            $value['username'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['head_pic'] = get_head_pic($value['head_pic']);
            $list[$key] = $value;
        }
        $show = $Page->show();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->assign('pager', $Page);

        // 是否开启文章付费
        $channelRow = Db::name('channeltype')->where('nid', 'in',['article','download'])->getAllWithIndex('nid');
        foreach ($channelRow as &$val){
            if (!empty($val['data'])) $val['data'] = json_decode($val['data'], true);
        }
        $this->assign('channelRow', $channelRow);

        return $this->fetch();
    }

    // 文章订单详情页
    public function article_order_details()
    {
        $order_id = input('param.order_id/d');
        if (!empty($order_id)) {
            $OrderData = Db::name('article_order')->field('*, product_id as aid')->find($order_id);
            $UsersData = $this->users_db->find($OrderData['users_id']);
            // 用于点击视频文档跳转到前台
            $array_new = get_archives_data([$OrderData], 'product_id');
            // 内页地址
            $OrderData['arcurl'] = get_arcurl($array_new[$OrderData['product_id']]);
            // 支持子目录
            $OrderData['product_litpic'] = get_default_pic($OrderData['product_litpic']);
            $this->assign('OrderData', $OrderData);
            $this->assign('UsersData', $UsersData);
            return $this->fetch();
        } else {
            $this->error('非法访问！');
        }
    }

    // 文章订单批量删除
    public function article_order_del()
    {
        $order_id = input('del_id/a');
        $order_id = eyIntval($order_id);
        if (IS_AJAX_POST && !empty($order_id)) {
            $Where = [
                'order_id'  => ['IN', $order_id],
            ];
            $result = Db::name('article_order')->field('order_code')->where($Where)->select();
            $order_code_list = get_arr_column($result, 'order_code');
            // 删除订单列表数据
            $return = Db::name('article_order')->where($Where)->delete();
            if ($return) {
                adminLog('删除文章订单：'.implode(',', $order_code_list));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    //积分明细
    public function users_score_detail()
    {
        $condition = [];
        $users_id = input('param.users_id/d');
        $condition['a.users_id'] = $users_id;

        $pagesize = 10;
        $count = Db::name('users_score')->alias('a')->where($condition)->count();
        $Page = new Page($count, $pagesize);
        $list = Db::name('users_score')
            ->alias('a')
            ->field('a.*,b.user_name,c.nickname')
            ->where($condition)
            ->join('admin b','a.admin_id = b.admin_id','left')
            ->join('users c','c.users_id = a.users_id','left')
            ->order('a.id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        $admin_ids = get_arr_column($list,'admin_id');

        $show = $Page->show();
        $this->assign('page',$show);
        $this->assign('list',$list);
        $this->assign('pager',$Page);

        $adminList = Db::name('admin')->where('admin_id','in',$admin_ids)->field('user_name,admin_id')->getAllWithIndex('admin_id');
        $this->assign('adminList', $adminList);
        // 积分类型
        $users_score_type_arr = config('global.users_score_type_arr');
        $this->assign('users_score_type_arr', $users_score_type_arr);

        return $this->fetch('member/edit/users_score_detail');
    }
    //余额明细
    public function users_money_detail()
    {
        $condition = [];
        $users_id = input('param.users_id/d');
        $condition['a.users_id'] = $users_id;
        $condition['a.status'] = ['in','2,3'];

        $pagesize = 10;
        $count = Db::name('users_money')->alias('a')->where($condition)->count();
        $Page = new Page($count, $pagesize);
        $list = Db::name('users_money')
            ->alias('a')
            ->field('a.*,b.user_name,c.nickname')
            ->where($condition)
            ->join('admin b','a.admin_id = b.admin_id','left')
            ->join('users c','c.users_id = a.users_id','left')
            ->order('a.moneyid desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $k => $v){
            if (0 == $v['cause_type']){
                $list[$k]['cause'] = unserialize($v['cause']);
            }
        }

        $show = $Page->show();
        $this->assign('page',$show);
        $this->assign('list',$list);
        $this->assign('pager',$Page);

        $add_type = [1,2,4]; //添加类型
        $reduce_type = [0,3,5]; //减少类型
        $this->assign('add_type',$add_type);
        $this->assign('reduce_type',$reduce_type);

        return $this->fetch('member/edit/users_money_detail');
    }
    // 余额充值
    public function users_edit_money()
    {
        $post = input('param.');
        $post['users_id'] = intval($post['users_id']);
        $users_id = $post['users_id'];
        $users = Db::name('users')->where('users_id',$users_id)->find();
        if (IS_POST){
            if (empty($post['type'])){
                $this->error('请选择变化！');
            }
            if (empty($post['money'])){
                $this->error('请输入充值数目！');
            }

            $insert['users_id'] = $users_id;
            $update['update_time'] = getTime();
            $cause_type = 4;// 4-管理员添加,5-管理员减少
            if (1 == $post['type']){
                //增加
                $update['users_money'] = Db::raw('users_money + '.$post['money']);
                $insert['money'] = $post['money'];
            }elseif (2 == $post['type']){
                //减少
                $update['users_money'] = Db::raw('users_money - '.$post['money']);
                $insert['money'] = $post['money'];
                $cause_type = 5;
            }elseif (3 == $post['type']){
                $update['users_money'] = $post['money'];
                if ($post['money'] > $users['users_money']){
                    $insert['money'] = $post['money'] - $users['users_money'];
                }else{
                    $insert['money'] = $users['users_money'] - $post['money'];
                    $cause_type = 5;
                }
            }

            $users_where = [
                'users_id' => $users_id,
            ];
            $update['update_time'] = getTime();
            $r = $this->users_db->where($users_where)->update($update);
            if ($r) {
                $insert['users_money'] = Db::name('users')->where($users_where)->value('users_money');
                $insert['admin_id'] = session('admin_id');
                $insert['cause'] = '管理员操作';
                $insert['remark'] = !empty($post['remark']) ? $post['remark'] : '';
                $insert['cause_type'] = $cause_type;
                $insert['status'] = 3;
                $insert['add_time'] = getTime();
                $insert['update_time'] = getTime();
                Db::name('users_money')->insert($insert);

                adminLog('编辑会员'.$users_id.'余额');
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }

        $this->assign('users',$users);
        return $this->fetch('member/edit/users_edit_money');
    }

    // 积分充值
    public function users_edit_score()
    {
        $post = input('param.');
        $post['users_id'] = intval($post['users_id']);
        $users_id = $post['users_id'];
        $users = Db::name('users')->where('users_id',$users_id)->find();
        if (IS_POST){
            if (empty($post['type'])){
                $this->error('请选择变化！');
            }
            if (empty($post['money'])){
                $this->error('请输入充值数目！');
            }

            $insert['type'] = 2;
            $insert['users_id'] = $users_id;
            $insert['add_time'] = $insert['update_time'] = $update['update_time'] = getTime();

            if (1 == $post['type']){
                //增加
                $update['scores'] = Db::raw('scores + '.$post['money']);
                $insert['score'] = $post['money'];
            }elseif (2 == $post['type']){
                //减少
                $update['scores'] = Db::raw('scores - '.$post['money']);
                $insert['score'] = $post['money'];
                $insert['rule'] = 1; //默认0增加,1-减少
                $insert['type'] = 3;
            }elseif (3 == $post['type']){
                $update['scores'] = $post['money'];
                if ($post['money'] > $users['scores']){
                    $insert['score'] = $post['money'] - $users['scores'];
                }else{
                    $insert['score'] = $users['scores'] - $post['money'];
                    $insert['rule'] = 1; //默认0增加,1-减少
                    $insert['type'] = 3;
                }
            }

            $users_where = [
                'users_id' => $users_id,
            ];
            $r = $this->users_db->where($users_where)->update($update);
            if ($r) {
                $insert['current_score'] = Db::name('users')->where($users_where)->value('scores');

                if (!empty($post['remark'])){
                    $insert['remark'] = $post['remark'];
                }
                $insert['admin_id'] = session('admin_id');
                Db::name('users_score')->insert($insert);

                \think\Cache::clear('users_list');

                adminLog('编辑会员'.$users_id.'UB');
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }

        $this->assign('users',$users);
        return $this->fetch('member/edit/users_edit_score');
    }

    // 下载订单列表页
    public function download_index()
    {
        // 定义数组
        $condition = [];

        // 订单状态搜索
        $order_status = input('param.order_status/d', 0);
        if (!empty($order_status)) $condition['a.order_status'] = intval($order_status) === 1 ? intval($order_status) : 0;

        // 订单号或用户名搜索
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $condition['a.order_code|b.username'] = ['LIKE', "%{$keywords}%"];

        // 支付方式查询
        $pay_name = input('pay_name/s', '');
        if (!empty($pay_name)) $condition['a.pay_name'] = $pay_name;

        // 时间检索条件
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $condition['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $condition['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $condition['a.add_time'] = array('elt', $end);
        }

        // 分页查询
        $count = Db::name('download_order')->alias('a')->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = Db::name('download_order')->where($condition)
            ->field('a.*, b.head_pic, b.username, b.nickname')
            ->alias('a')
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.order_id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $key => $value) {
            $value['username'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['head_pic'] = get_head_pic($value['head_pic']);
            $list[$key] = $value;
        }
        $show = $Page->show();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->assign('pager', $Page);

        // 是否开启文章付费
        $channelRow = Db::name('channeltype')->where('nid', 'in',['article','download'])->getAllWithIndex('nid');
        foreach ($channelRow as &$val){
            if (!empty($val['data'])) $val['data'] = json_decode($val['data'], true);
        }
        $this->assign('channelRow', $channelRow);

        return $this->fetch();
    }

    // 文章订单详情页
    public function download_order_details()
    {
        $order_id = input('param.order_id/d');
        if (!empty($order_id)) {
            $OrderData = Db::name('download_order')->field('*, product_id as aid')->find($order_id);
            $UsersData = $this->users_db->find($OrderData['users_id']);
            // 用于点击视频文档跳转到前台
            $array_new = get_archives_data([$OrderData], 'product_id');
            // 内页地址
            $OrderData['arcurl'] = get_arcurl($array_new[$OrderData['product_id']]);
            // 支持子目录
            $OrderData['product_litpic'] = get_default_pic($OrderData['product_litpic']);
            $this->assign('OrderData', $OrderData);
            $this->assign('UsersData', $UsersData);
            return $this->fetch('article_order_details');
        } else {
            $this->error('非法访问！');
        }
    }

    // 文章订单批量删除
    public function download_order_del()
    {
        $order_id = input('del_id/a');
        $order_id = eyIntval($order_id);
        if (IS_AJAX_POST && !empty($order_id)) {
            $Where = [
                'order_id'  => ['IN', $order_id],
            ];
            $result = Db::name('download_order')->field('order_code')->where($Where)->select();
            $order_code_list = get_arr_column($result, 'order_code');
            // 删除订单列表数据
            $return = Db::name('download_order')->where($Where)->delete();
            if ($return) {
                adminLog('删除下载订单：'.implode(',', $order_code_list));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // 用户收藏列表
    public function eyou_collect_index()
    {
        // 查询条件
        $users_id = input('param.users_id/d');
        $where['b.users_id'] = $users_id;

        $keywords = input('keywords/s');
        if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

        $count = Db::name('users_collection')
            ->alias('b')
            ->join('archives a','b.aid = a.aid','left')
            ->where($where)
            ->count('id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $this->assign('page', $pageObj->show());
        $this->assign('pager', $pageObj);

        $field = 'b.*,a.users_price,a.status,a.title';
        $list = Db::name('users_collection')
            ->alias('b')
            ->field($field)
            ->join('archives a','b.aid = a.aid','left')
            ->where($where)
            ->order('a.sort_order asc, a.users_price desc, a.aid desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        if (!empty($list)){
            $ids = get_arr_column($list,'id');
            $counts = Db::name('users_collection')->where('id','in',$ids)->group('id')->field('id,count(*) as count')->getAllWithIndex('id');
            foreach ($list as $k => $v){
                $list[$k]['collect_count'] = !empty($counts[$v['id']]) ? $counts[$v['id']]['count'] : 0;
            }
        }

        $this->assign('list', $list);
        $this->assign('users_id', $users_id);

        return $this->fetch('member/edit/eyou_collect_index');
    }

    // 用户足迹列表
    public function eyou_footprint_index()
    {
        // 查询条件
        $users_id = input('param.users_id/d');
        $where['b.users_id'] = $users_id;

        $keywords = input('keywords/s');
        if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

        $count = Db::name('users_footprint')
            ->alias('b')
            ->join('archives a','b.aid = a.aid','left')
            ->where($where)
            ->count('id');

        $pageObj = new Page($count, config('paginate.list_rows'));
        $this->assign('page', $pageObj->show());
        $this->assign('pager', $pageObj);

        $field = 'b.*,a.users_price,a.status,a.click,a.title';
        $list = Db::name('users_footprint')
            ->alias('b')
            ->field($field)
            ->join('archives a','b.aid = a.aid','left')
            ->where($where)
            ->order('a.sort_order asc, a.users_price desc, a.aid desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();

        $this->assign('list', $list);
        $this->assign('users_id', $users_id);

        return $this->fetch('member/edit/eyou_footprint_index');
    }
}